package com.deyuanyun.pic.pipe.support.validatefun;

import com.caixu.beanvalidateutil.annotations.CodeVail;
import com.caixu.beanvalidateutil.vinterface.ValidateInterface;
import com.deyuanyun.pic.support.biz.CodeUtil;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;

import java.lang.reflect.Field;
import java.util.List;

public class CodeValidata implements ValidateInterface {

	String name="";
	
	@Override
	public <T, E,C> boolean apply(T t, E e,C c) {
		//CodeUtil codeUtil=SpringAppliction.getBean(CodeUtil.class);
		if (t==null || "".equals(t)){return true;}
		Field field=(Field) e;
		CodeVail vail=field.getAnnotation(CodeVail.class);
		if(vail != null || StringUtils.isNotBlank(vail.majorCode()))
		{
			List<String> data=CodeUtil.getCodeListString(vail.majorCode());
			if(data.contains(t) )
			{
				String id_ = CodeUtil.getCodeId(vail.majorCode(),(String) t);
				try {
					BeanUtils.setProperty(c,field.getName(),id_);
				} catch (Exception e1) {
					e1.printStackTrace();
					return false;
				}
				return true;
			}
			String ts=(String)t;
			if (StringUtils.endsWith(ts,".0")){
				ts=StringUtils.removeEnd(ts,".0");
				if (data.contains(ts)){
					String id_ = CodeUtil.getCodeId(vail.majorCode(),(String) ts);
					try {
						BeanUtils.setProperty(c,field.getName(),id_);
					} catch (Exception e1) {
						e1.printStackTrace();
						return false;
					}
					return true;
				}
			}
		}
		return false;
	}

	@Override
	public String getName() {
		
		return name;
	}

}
